package cnsukidayo.com.gitee.service.impl;

import cnsukidayo.com.gitee.handler.properties.THPetContextProperties;
import cnsukidayo.com.gitee.mapper.PetMapper;
import cnsukidayo.com.gitee.model.pojo.Pet;
import cnsukidayo.com.gitee.model.vo.PetVO;
import cnsukidayo.com.gitee.service.PetService;
import cnsukidayo.com.gitee.utils.Resources;
import org.fisco.bcos.sdk.abi.ABICodecException;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.crypto.keypair.CryptoKeyPair;
import org.fisco.bcos.sdk.transaction.manager.AssembleTransactionProcessor;
import org.fisco.bcos.sdk.transaction.manager.TransactionProcessorFactory;
import org.fisco.bcos.sdk.transaction.model.dto.TransactionResponse;
import org.fisco.bcos.sdk.transaction.model.exception.TransactionBaseException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sukidayo
 * @date 2023/3/26 10:08
 */
@Service
public class PetServiceImpl implements PetService {

    private final Client client;
    private PetMapper petMapper;

    public PetServiceImpl(Client client,
                          PetMapper petMapper) {
        this.client = client;
        this.petMapper = petMapper;
    }

    @Override
    public PetVO queryPetWithID(int id) {
        // 查询宠物对应的收留所ID
        Pet pet = petMapper.queryPetById(id);
        CryptoKeyPair keyPair = client.getCryptoSuite().createKeyPair();
        AssembleTransactionProcessor transactionProcessor = null;
        try {
            transactionProcessor = TransactionProcessorFactory.createAssembleTransactionProcessor(client, keyPair, Resources.getResource("abi"), "");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        TransactionResponse transactionResponse;
        try {
            List<Object> params0 = new ArrayList<>();
            params0.add(id);
            transactionResponse = transactionProcessor.sendTransactionAndGetResponseByContractLoader("PetContract", THPetContextProperties.PET_CONTRACT, "getPet", params0);
        } catch (ABICodecException e) {
            throw new RuntimeException(e);
        } catch (TransactionBaseException e) {
            throw new RuntimeException(e);
        }
        PetVO petVO = new PetVO();
        petVO.setId((Integer) ((List<?>) transactionResponse.getValuesList().get(0)).get(0));
        petVO.setName((String) ((List<?>) transactionResponse.getValuesList().get(0)).get(1));
        petVO.setGender((String) ((List<?>) transactionResponse.getValuesList().get(0)).get(2));
        petVO.setAdopted((Boolean) ((List<?>) transactionResponse.getValuesList().get(0)).get(3));
        petVO.setTimestamp((Long) ((List<?>) transactionResponse.getValuesList().get(0)).get(4));
        petVO.setShelterID(pet.getPetShelter());
        return petVO;
    }
}
